package com.yuezhu.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.yuezhu.R;
import com.yuezhu.been.DataChangedEvent;
import com.yuezhu.been.UserMsg;
import com.yuezhu.constante.BusAction;
import com.yuezhu.control.TaskEngine;
import com.yuezhu.global.BaseActivity;
import com.yuezhu.util.LogUtils;
import com.yuezhu.util.MyToast;
import com.yuezhu.util.NetworkUtils;
import com.yuezhu.util.ResponseUtil;
import com.yuezhu.util.StringUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.ButterKnife;
import butterknife.InjectView;

public class LoginActivity extends BaseActivity {

    @InjectView(R.id.et_login_phonenumber)
    EditText etLoginPhonenumber;
    @InjectView(R.id.et_login_password)
    EditText etLoginPassword;
    @InjectView(R.id.iv_bottome_left)
    ImageView ivBottomeLeft;
    @InjectView(R.id.iv_bottome_right)
    ImageView ivBottomeRight;
    @InjectView(R.id.iv_bottome_middle)
    ImageView ivBottomeMiddle;
    @InjectView(R.id.tv_forget_passsword)
    TextView tvForgetPasssword;
    @InjectView(R.id.iv_menu)
    ImageView ivMenu;
    @InjectView(R.id.tv_title)
    TextView tvTitle;
    @InjectView(R.id.iv_quite)
    ImageView ivQuite;
    @InjectView(R.id.tv_version)
    TextView tvVersion;
    private String namePhoneEmail;
    private String password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.inject(this);
        initView();
        setListeners();
        EventBus.getDefault().register(this);
        if (getIntent().getStringExtra("userName") != null) {
            etLoginPhonenumber.setText(getIntent().getStringExtra("userName"));
        }
    }


    @Override
    protected void initView() {
        ivMenu.setImageResource(R.drawable.zhuoyun);
        tvTitle.setText("用户登录");
        //设置忘记密码和发送邮件下划线
        tvForgetPasssword.setText(Html.fromHtml("<u>" + "忘记密码" + "</u>"));
        ivBottomeLeft.setImageResource(R.drawable.signup);
        ivBottomeRight.setImageResource(R.drawable.login);
    }

    @Override
    protected void setListeners() {
        ivBottomeLeft.setOnClickListener(this);
        ivBottomeRight.setOnClickListener(this);
        ivQuite.setOnClickListener(this);
        etLoginPhonenumber.addTextChangedListener(new PhoneNumWatcher());
        etLoginPassword.addTextChangedListener(new PassWordWatcher());
        tvForgetPasssword.setOnClickListener(this);
    }

    @Subscribe
    public void onEventMainThread(BusAction.quitApp event) {
        finish();
    }

    @Subscribe
    public void onEventMainThread(BusAction.signupSucceed event) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    // 订阅事件DataChangedEvent
    public void setCardEvent(DataChangedEvent event) {
        switch (event.getAction()) {
            case BusAction.QUIT_APP:
                finish();
                break;
            case BusAction.SIGNUP_SUCCEED:
//                String userName = UserMsg.getInstance().getUserName();
            default:
                break;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_bottome_left:
                startParallaxSwipeBackActivty(LoginActivity.this, new Intent(LoginActivity.this, SignUpActivity.class));
                break;
            case R.id.iv_bottome_right:
                if (StringUtil.isEmpty(namePhoneEmail)) {
                    MyToast.showDefaltToast("用户名/邮件/手机不能为空");
                    return;
                }
                if (StringUtil.isEmpty(password)) {
                    MyToast.showDefaltToast("密码不能为空");
                    return;
                }
                if (NetworkUtils.isNetworkAvailable(getApplicationContext())) {
                    //访问网络登录
                    TaskEngine.getInstance().startLoginTask(queue, namePhoneEmail, password, ResponseLis, Errorlis);
                } else {
                    MyToast.showDefaltToast("网络不可用");
                }
                break;
            case R.id.iv_quite:
                finish();
                System.exit(0);
                break;
            case R.id.tv_forget_passsword:
                String url = "http://www.zcloud-online.com/userservice/forgetpassword.jsp";
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                Uri content_url = Uri.parse(url);
                intent.setData(content_url);
                startActivity(intent);
                break;
        }
    }


    class PhoneNumWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            namePhoneEmail = s.toString().trim();

        }
    }

    class PassWordWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            password = s.toString().trim();

        }
    }

    // 注册成功
    Response.Listener ResponseLis = new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject json) {
            LogUtils.e("登录成功" + "sec" + json.toString());
            try {
                String respDesc = json.getString("respDesc");
                String respCode = json.getString("respCode");
                int respNo = json.getInt("respNo");
                if (!StringUtil.equal(respCode, "OK")) {
                    if (respNo == ResponseUtil.USER_NOT_ACTIVATION) {
                        Intent intent = new Intent(LoginActivity.this, SendMailActivity.class);
                        intent.putExtra("authToken", json.getString("authToken"));
                        startActivity(intent);
                    }
                    MyToast.showDefaltToast(respDesc);
                } else {
                    MyToast.showDefaltToast(respDesc);
                    UserMsg userMsg = UserMsg.getInstance();
                    userMsg.setUserName(json.getString("userName"));
                    userMsg.setAuthToken(json.getString("authToken"));
                    userMsg.setLevel(json.getInt("level"));
                    startActivity(new Intent(LoginActivity.this, MyprojectActivity.class));
                    finish();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    };

    /**
     * 注册失败
     */
    Response.ErrorListener Errorlis = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            LogUtils.e("登录失败", "error  " + volleyError.toString());
        }
    };
}
